package com.yuncheng.spcyApi.flow;

import cn.hutool.core.collection.CollectionUtil;
import com.yuncheng.entity.YcSysUser;
import com.yuncheng.spcyApi.constant.schedule.ScheduleConstant;
import com.yuncheng.spcyApi.dto.FlowJobHistoryDto;
import com.yuncheng.spcyApi.scheduleJob.ScheduleJobService;
import com.yuncheng.spcyApi.vo.flow.SpcyJobXqVo;
import com.yuncheng.spcyApi.vo.spcy.SpcyXpryUserVo;
import com.yuncheng.vo.GetKsKz;
import com.yuncheng.vo.CurrentUserVo;
import org.apache.commons.collections.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.yuncheng.spcyApi.busService.BusService;
import com.yuncheng.spcyApi.busService.FlowJobBlsxService;
import com.yuncheng.spcyApi.constant.common.LogConstant;
import com.yuncheng.spcyApi.constant.common.SpcyCommonConstant;
import com.yuncheng.spcyApi.constant.common.SpcyConstant;
import com.yuncheng.spcyApi.entity.*;
import com.yuncheng.exception.BusinessException;
import com.yuncheng.spcyApi.selectXzxkApi.vo.PutBqbzVo;
import com.yuncheng.spcyApi.selectXzxkApi.vo.XzspJkApiJsywbmthParamVo;
import com.yuncheng.spcyApi.selectXzxkApi.vo.XzspJkApiJsywbmthVo;
import com.yuncheng.spcyApi.service.*;
import com.yuncheng.spcyApi.service.impl.YcSysUserServiceImpl;
import com.yuncheng.spcyApi.spcyService.SpcyHbjcService;
import com.yuncheng.spcyApi.spcyService.SpcyVerifyService;
import com.yuncheng.spcyApi.spcyService.XpryTimedTasksService;
import com.yuncheng.spcyApi.utils.GetCurrentUserUtils;
import com.yuncheng.spcyApi.utils.StringPatternUtils;
import com.yuncheng.spcyApi.vo.common.Result;
import com.yuncheng.spcyApi.vo.flow.AgentVo;
import com.yuncheng.spcyApi.vo.spcy.SpcyReturnVo;
import com.yuncheng.spcyApi.vo.sqsx.SqsxZbrVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import utils.LogUtils;
import utils.ObjectToMapUtils;

import javax.annotation.Resource;
import java.util.*;

@Component(value = "spcyFlowService")
public class SpcyFlowService {

    private static final Logger log = LoggerFactory.getLogger(SpcyFlowService.class);

    @Resource
    @Lazy
    private ISysUserFgldService sysUserFgldService;

    @Resource
    @Lazy
    private ISpcySqsxXpjlService spcySqsxXpjlService;

    @Resource
    @Lazy
    private ISpcySqsxJobService spcySqsxJobService;

    @Resource
    @Lazy
    private ISpcySqsxBaiscService spcySqsxBaiscService;

    @Resource
    @Lazy
    private ISpcyQyJbxxService spcyQyJbxxService;

    @Resource
    @Lazy
    private YcSysUserServiceImpl ycSysUserService;

    @Resource
    @Lazy
    private FlowJobBlsxService flowJobBlsxService;

    @Resource
    @Lazy
    private BusService busService;

    @Resource
    @Lazy
    private ISysFlowNodeService sysFlowNodeService;

    @Resource
    @Lazy
    private FlowNodeService flowNodeService;

    @Resource
    @Lazy
    private ISpcyLogService spcyLogService;

    @Resource
    @Lazy
    private SpcyVerifyService spcyVerifyService;

    @Resource
    @Lazy
    private ThzwYpscFlowService thzwYpscFlowService;

    @Resource
    private XpryTimedTasksService xpryTimedTasksService;

    @Resource
    private BqbzFlowService bqbzFlowService;

    @Resource
    private SpcyHbjcService spcyHbjcService;

    @Resource
    private ISpcySqsxRcjgService spcySqsxRcjgService;

    @Resource
    @Lazy
    private ScheduleJobService scheduleJobService;

    /**
     * 处理流程
     * @param flowVo
     * @param jobId
     * @param submitType
     * @param opinion
     * @return
     */
    public Result handleFlow(FlowVo flowVo, String jobId, String submitType, String opinion){
        return handleFlow(flowVo, jobId, null, submitType, opinion);
    }
    public Result handleFlow(FlowVo flowVo, String jobId, SpcySqsxJob nowJob, String submitType, String opinion){
        // 当前流程任务
        if (nowJob == null) {
            nowJob = spcySqsxJobService.getById(jobId);

            if (nowJob == null) {
                throw new BusinessException("当前流程任务不存在，请刷新重试！");
            }
        }
        String sqsxid = nowJob.getFpid();

        // 任务受理
        if (nowJob.getFhjmc().equals(SpcyFlowConstant.HJMC_RWSL)) {

            spcyVerifyService.verifySpcyFlowNodeRwsl(sqsxid, submitType, true, flowVo);

            /** 日常检查验证是否跳转环节 */
            /*if (submitType.equals(SpcyFlowConstant.SUBMIT_TYPE_SUBMIT)) {
                boolean jumpFhjmc = spcySqsxBaiscService.getSqsxRcjgAndZxjcJumpHjmc(sqsxid);
                if (jumpFhjmc) {
                    flowVo.setNextNode(SpcyFlowConstant.HJMC_FAZZ);
                }
            }*/

            flowVo.setDbrid(null);
            // 流程环节处理
            Result httpResult = handleNodeName(flowVo, submitType, nowJob, sqsxid, opinion);
            if (!httpResult.isSuccess()){
                return httpResult;
            }

            spcyVerifyService.verifySpcyFlowNodeRwsl(sqsxid, submitType, false, flowVo);

            return httpResult;
        }
        /*else if (nowJob.getFhjmc().equals(SpcyFlowConstant.HJMC_CLSC)){

            spcyVerifyService.verifySpcyFlowNodeClsc(flowVo, sqsxid, submitType, true, nowJob);

//            flowVo.setDbrid(null);
            // 流程环节处理
            Result httpResult = handleNodeName(flowVo, submitType, nowJob, sqsxid, opinion);
            if (!httpResult.isSuccess()){
                return httpResult;
            }

            spcyVerifyService.verifySpcyFlowNodeClsc(flowVo, sqsxid, submitType, false, nowJob);

        }*/
        /*else if (nowJob.getFhjmc().equals(SpcyFlowConstant.HJMC_CLSCFH)){

            spcyVerifyService.verifySpcyFlowNodeClscFh(sqsxid, submitType, true, null);

//            flowVo.setDbrid(null);
            SpcySqsxBasic sqsx = null;
            if (submitType.equals(SpcyFlowConstant.SUBMIT_TYPE_SUBMIT)) {
                sqsx = spcySqsxBaiscService.selectSqsxById(sqsxid);
                if (StringUtils.isNotBlank(sqsx.getFclscms()) && sqsx.getFclscms().equals(SpcyCommonConstant.SQSX_CLSCMS_NO_XCJC)) {
                    flowVo.setNextNode(SpcyFlowConstant.HJMC_ZHPD);
                }
            }

            // 流程环节处理
            Result httpResult = handleNodeName(flowVo, submitType, nowJob, sqsxid, opinion);
            if (!httpResult.isSuccess()){
                return httpResult;
            }

            spcyVerifyService.verifySpcyFlowNodeClscFh(sqsxid, submitType, false, sqsx);

        }*/
        else if (nowJob.getFhjmc().equals(SpcyFlowConstant.HJMC_FAZZ)){

            spcyVerifyService.verifySpcyFlowNodeFazz(sqsxid, submitType, true, nowJob);

//            flowVo.setDbrid(null);
            // 流程环节处理
            Result httpResult = handleNodeName(flowVo, submitType, nowJob, sqsxid, opinion);
            if (!httpResult.isSuccess()){
                return httpResult;
            }

            spcyVerifyService.verifySpcyFlowNodeFazz(sqsxid, submitType, false, nowJob);

        }
//        else if (nowJob.getFhjmc().equals(SpcyFlowConstant.HJMC_FASP)){
        else if (nowJob.getFhjmc().equals(SpcyFlowConstant.HJMC_FASH)){

            spcyVerifyService.verifySpcyFlowNodeFasp(sqsxid, submitType, nowJob, true);

            flowVo.setDbrid(null);
            // 流程环节处理
            Result httpResult = handleNodeName(flowVo, submitType, nowJob, sqsxid, opinion);
            if (!httpResult.isSuccess()){
                return httpResult;
            }

            spcyVerifyService.verifySpcyFlowNodeFasp(sqsxid, submitType, nowJob, false);

        }
        else if (nowJob.getFhjmc().equals(SpcyFlowConstant.HJMC_JSSP)){

            /** 验证是否合并事项 */
            SpcySqsxBasic sqsx = null;
            if (submitType.equals(SpcyFlowConstant.SUBMIT_TYPE_SUBMIT)) {
                sqsx = spcySqsxBaiscService.selectSqsxInfoById(sqsxid);
            }

            spcyVerifyService.verifySpcyFlowNodeXcjc(flowVo, sqsxid, submitType, true, sqsx);

            /** 验证是否合并事项 */
//            boolean isHbsx = spcyHbjcService.verifySqsxIsHbsqsx(sqsxid, sqsx);

            flowVo.setDbrid(null);
//            if (!isHbsx) {
                // 现场检查
                // 流程环节处理
                Result httpResult = handleNodeName(flowVo, submitType, nowJob, sqsxid, opinion);
                if (!httpResult.isSuccess()) {
                    return httpResult;
                }
            /*}else {
                *//** 合并事项 *//*
                *//** 创建待办 *//*
                Result result = spcyHbjcService.bhbsxRecoveryZhpdJobByXcjc(sqsxid, sqsx, nowJob, opinion, submitType);
                if (!result.isSuccess()){
                    return result;
                }
            }*/

            spcyVerifyService.verifySpcyFlowNodeXcjc(flowVo, sqsxid, submitType, false, sqsx);
        }
        /*else if (nowJob.getFhjmc().equals(SpcyFlowConstant.HJMC_ZHPD)){

            spcyVerifyService.verifySpcyFlowNodeZhpd(sqsxid, submitType, true, flowVo);

            // 综合评定
            // 流程环节处理
            Result httpResult = handleNodeName(flowVo, submitType, nowJob, sqsxid, opinion);
            if (!httpResult.isSuccess()){
                return httpResult;
            }

        }*/
        /*else if (nowJob.getFhjmc().equals(SpcyFlowConstant.HJMC_ZHPD_FH)){

            spcyVerifyService.verifySpcyFlowNodeZhpdFh(sqsxid, submitType, true, flowVo);

            // 流程环节处理
            Result httpResult = handleNodeName(flowVo, submitType, nowJob, sqsxid, opinion);
            if (!httpResult.isSuccess()){
                return httpResult;
            }

        }*/
//        else if (nowJob.getFhjmc().equals(SpcyFlowConstant.HJMC_YSQR)){
        else if (nowJob.getFhjmc().equals(SpcyFlowConstant.HJMC_ZHPD)){

            spcyVerifyService.verifySpcyFlowNodeYsrq(sqsxid, submitType, true);

            // 移送确认
            // 流程环节处理
            Result httpResult = handleNodeName(flowVo, submitType, nowJob, sqsxid, opinion);
            if (!httpResult.isSuccess()){
                return httpResult;
            }

            spcyVerifyService.verifySpcyFlowNodeYsrq(sqsxid, submitType, false);

        }else if (nowJob.getFhjmc().equals(SpcyFlowConstant.THZW_HJMC_THZWSH)){

            // 流程环节处理
            Result httpResult = thzwYpscFlowService.handleFlow(flowVo, jobId, nowJob, sqsxid, submitType, opinion);
            if (!httpResult.isSuccess()){
                return httpResult;
            }

        }else if (nowJob.getFhjmc().equals(SpcyFlowConstant.THZW_HJMC_THZWSP)){

            // 流程环节处理
            Result httpResult = thzwYpscFlowService.handleFlow(flowVo, jobId, nowJob, sqsxid, submitType, opinion);
            if (!httpResult.isSuccess()){
                return httpResult;
            }

        }else if (nowJob.getFhjmc().equals(SpcyFlowConstant.HJMC_BQBZSH)){

            PutBqbzVo putBqbzVo = new PutBqbzVo();
            putBqbzVo.setOpinion(flowVo.getOpinion());
            putBqbzVo.setJobid(jobId);
            putBqbzVo.setSqsxid(sqsxid);
            putBqbzVo.setFsqsxid(sqsxid);
            putBqbzVo.setSmgflag(flowVo.getSmgflag());

            Result httpResult = bqbzFlowService.passNextNodeFlow(putBqbzVo, jobId, nowJob, sqsxid, opinion);
            if (!httpResult.isSuccess()){
                return httpResult;
            }

        }else {
            Result httpResult = handleNodeName(flowVo, submitType, nowJob, sqsxid, opinion);
            if (!httpResult.isSuccess()){
                return httpResult;
            }
        }

        return Result.ok("操作成功");
    }

    /**
     * 流程环节处理
     * @param sqsxid 申请信息id
     * @param flowVo 需要修改的字段内容
     * @param job 流程任务job
     * @param opinion 办理意见
     * @param submitType 提交、保存类型
     * @return true(),false(提示信息)
     */
    public Result handleNodeName(FlowVo flowVo,String submitType, SpcySqsxJob job, String sqsxid, String opinion){
        HashMap<String, Object> map = flowVo.getMap();
        String smgflag = flowVo.getSmgflag(); // 短信发送标志
        String smsContent = flowVo.getSmsContent(); // 发送短信内容

        Result res = null;

        // 保存按钮
        if (submitType.equals(SpcyFlowConstant.SUBMIT_TYPE_SAVE)){
            res = busService.updateSqsxBasic(map, sqsxid, job);
            if (!res.isSuccess()){
                return res;
            }else {
                return Result.ok("保存成功");
            }
        }

        // 提交按钮
        if (submitType.equals(SpcyFlowConstant.SUBMIT_TYPE_SUBMIT)){

            res = busService.updateSqsxBasic(map, sqsxid, job);

            if (!res.isSuccess()){
                return res;
            }

            // 流程任务id
            String jobid = job.getId();

            // 提交流程任务,待办人是否为空，指定待办人
            if (StringUtils.isBlank(flowVo.getDbrid())) {
                // 按审查模式-提交-流程任务
                res = this.passJob(sqsxid, jobid, job, opinion, flowVo.getNextNode(),flowVo.getNextNodeId(), null);
            }else {
                // 按审查模式-提交-流程任务
                res = this.passJob(sqsxid, jobid, job, opinion, flowVo.getNextNode(),flowVo.getNextNodeId(),flowVo.getDbrid());
            }
            if (!res.isSuccess()){
                return res;
            }else {

                if (StringUtils.isNotBlank(flowVo.getNextNode()) && flowVo.getNextNode().equals(SpcyFlowConstant.HJMC_ZHPD)){
                    spcyVerifyService.verifySpcyFlowJumpZhpdNode(sqsxid);
                }

                /**
                 * 接收返回的流程任务，如果返回的流程任务id不相等，发送短信
                 * 发送下环节短信
                 */
                if (StringUtils.isNotBlank(smgflag) && (smgflag.equals("是") || smgflag.equals("true"))){
                    busService.sendSmsToNextJob(jobid,smsContent);
                }
            }
        }

        return Result.ok("提交成功");
    }

    /**
     * 退回政务服务-流程环节处理
     * @param flowVo 需要修改的字段内容
     * @param opinion 办理意见
     * @param submitType 提交、保存类型
     * @return true(),false(提示信息)
     */
    public Result handleThzwfwNodeName(FlowVo flowVo, String jobId, String submitType, String opinion){
        return handleThzwfwNodeName(flowVo, jobId, null, submitType, opinion);
    }
    public Result handleThzwfwNodeName(FlowVo flowVo, String jobId, SpcySqsxJob nowJob, String submitType, String opinion){
        if (nowJob == null) {
            nowJob = spcySqsxJobService.getById(jobId);

            if (nowJob == null) {
                throw new BusinessException("当前流程任务不存在，请刷新重试！");
            }
        }

        flowVo.setDbrid(null);
        if (nowJob.getFhjmc().equals(SpcyFlowConstant.HJMC_CLSC)){

            Result httpResult = thzwYpscFlowService.passNextNodeFlow(flowVo, jobId, nowJob.getFpid(),SpcyFlowConstant.THZW_HJMC_THZWSH, opinion);
            if (!httpResult.isSuccess()){
                return httpResult;
            }

            if (submitType.equals(SpcyFlowConstant.SUBMIT_TYPE_SUBMIT)){
                spcySqsxBaiscService.updateSqsxByThzwfwYj(nowJob.getFpid(), opinion, flowVo.getSmsContent());
            }

        }else if (nowJob.getFhjmc().equals(SpcyFlowConstant.HJMC_CLSCFH)){

            Result httpResult = thzwYpscFlowService.passNextNodeFlow(flowVo, jobId, nowJob.getFpid(),SpcyFlowConstant.THZW_HJMC_THZWSP, opinion);
            if (!httpResult.isSuccess()){
                return httpResult;
            }

            if (submitType.equals(SpcyFlowConstant.SUBMIT_TYPE_SUBMIT)){
                spcySqsxBaiscService.updateSqsxByThzwfwYj(nowJob.getFpid(), opinion, flowVo.getSmsContent());
            }

        }else {

            Result httpResult = thzwYpscFlowService.handleFlow(flowVo, jobId, nowJob, "", submitType, opinion);
            if (!httpResult.isSuccess()){
                return httpResult;
            }

        }

        return Result.ok("操作成功");
    }

    /**
     * 初始业务分类编码对应的流程
     * @param fywflcode
     * @param sqsxid
     * @param currentUser
     * @param isSendSms 是否发送短信（true: 发送）
     * @return
     */
    public Result initYwflJob(String fywflcode,String sqsxid,CurrentUserVo currentUser,boolean isSendSms){
        String flowCode = SpcyFlowConstant.getFlowCodeByYwflcode(fywflcode, SpcyConstant.SQSX_BASIC_XZSPZT_YES);

        return this.createProcess(flowCode,sqsxid,currentUser,isSendSms);
    }

    /**
     * 初始化流程
     * @param lcmbCode 流程模板编码
     * @param sqsxid 申请事项id
     * @param currentUser 当前登陆用户
     * @param isSendSms 是否发送短信
     * @return
     */
    public Result createProcess(String lcmbCode, String sqsxid, CurrentUserVo currentUser, boolean isSendSms){

        //获取流程模板的第一个环节
        SysFlowTemple code = sysFlowNodeService.getCode(lcmbCode);

        List<SysFlowNode> node = sysFlowNodeService.getFirstNode(code.getId());

        List<SpcySqsxJob> jobList = spcySqsxJobService.list(new LambdaQueryWrapper<SpcySqsxJob>()
                .eq(SpcySqsxJob::getFpid, sqsxid)
                .eq(SpcySqsxJob::getFnodeid, node.get(0).getId())
                .ne(SpcySqsxJob::getFblzt, SpcyConstant.BLZT_YB));
        if (CollectionUtils.isNotEmpty(jobList)){
            return Result.error("当前申请事项环节["+node.get(0).getFjdmc()+"】已经初始化了!");
        }

        Result result = flowNodeService.createJob(lcmbCode,sqsxid,"",node.get(0),null,null,currentUser);
        if (!result.isSuccess()){
            return result;
        }else {
            if (isSendSms) {
                SpcySqsxJob job = (SpcySqsxJob) result.getResult();
                if (job != null) {
                    String nextNodeSmsContent = busService.getNextNodeSmsContent(job, null);
                    busService.sendSmsToNodeDbr(job.getFdbrid(), job.getFlcmc() + "-" + job.getFhjmc(), nextNodeSmsContent);
                }
            }
        }

        return result;
    }

    /**
     * 提取政务系统已经存在对应的事项
     * */
    public void existsReturnZwxtSqsx(String sqsxid){
        SpcySqsxJob nowDbJob = null;
        List<SpcySqsxJob> jobDbList = spcySqsxJobService.list(new LambdaQueryWrapper<SpcySqsxJob>()
                .eq(SpcySqsxJob::getFpid, sqsxid)
                .eq(SpcySqsxJob::getFhjmc, SpcyFlowConstant.HJMC_CLSC)
                .ne(SpcySqsxJob::getFblzt, SpcyConstant.BLZT_YB));
        if (CollectionUtil.isEmpty(jobDbList)){
            /** 审评查验流程-当前待办环节 */
            List<SpcySqsxJob> jobYbList = spcySqsxJobService.list(new LambdaQueryWrapper<SpcySqsxJob>()
                    .eq(SpcySqsxJob::getFpid, sqsxid)
                    .eq(SpcySqsxJob::getFhjmc, SpcyFlowConstant.HJMC_CLSC)
                    .eq(SpcySqsxJob::getFblzt, SpcyConstant.BLZT_YB)
                    .orderByDesc(SpcySqsxJob::getFfssj));
            if (CollectionUtil.isNotEmpty(jobYbList)){
                nowDbJob = jobYbList.get(0);

                /** 创建待办 */
                flowNodeService.copyNewJob(SpcyConstant.BLZT_DB, sqsxid,
                        "", "",
                        "", "",
                        nowDbJob, null,
                        "", "");

                spcySqsxBaiscService.updateHfSqsxThzwfw(sqsxid);

                scheduleJobService.pushXzspDataByJkType(sqsxid, ScheduleConstant.Xzsp_Data_Rwsl_Code);
            }
        }
    }

    /**
     * 删除流程-通过流程任务id
     */
    public void deleteFlowJob(String jobids){
        List<String> jobidList = StringPatternUtils.getListByIds(jobids);
        if (CollectionUtils.isNotEmpty(jobidList)){
            for (String id : jobidList) {
                SpcySqsxJob job = spcySqsxJobService.getById(id);
                if (job == null){
                    log.error("删除流程-通过流程任务id：出错{}id为空，流程不存在。",id);
                    continue;
                }

                // 删除申请事项
                SpcySqsxBasic sqsx = spcySqsxBaiscService.getById(job.getFpid());
                if (sqsx != null && !sqsx.getFxzspzt().equals(SpcyConstant.SQSX_BASIC_XZSPZT_YES)) {

                    spcySqsxJobService.remove(new LambdaQueryWrapper<SpcySqsxJob>()
                            .eq(SpcySqsxJob::getFpid, id));

                    boolean flag = spcySqsxBaiscService.removeById(job.getFpid());// 删除申请事项
                    if (flag) {
                        String log = "";
                        log += LogUtils.MapToStringMethod(ObjectToMapUtils.objectToMap(sqsx));
                        spcyLogService.addLogs(job.getFhjmc(), log, job.getFpid(), LogConstant.LOGS_SQSX_BASIC, SpcyConstant.LOGS_SYS_TYPE_SC);
                    }
                }

                String lognr = "删除申请事项-流程: ";
                Map<String, Object> jobMap = ObjectToMapUtils.objectToMap(job);
                lognr += LogUtils.MapToStringMethod(jobMap);
                spcyLogService.addLogs(job.getFhjmc(),lognr,job.getFpid(), LogConstant.LOGS_SQSX_JOB, SpcyConstant.LOGS_SYS_TYPE_SC);
            }
        }

    }

    /**
     * 获取申请事项-审评查验-最新的流程待办任务
     * @param pid 业务id
     */
    public SpcySqsxJob getNewSpcyJobDb(String pid){

        List<SpcySqsxJob> jobList = spcySqsxJobService.list(new LambdaQueryWrapper<SpcySqsxJob>()
                .eq(SpcySqsxJob::getFpid, pid)
                .ne(SpcySqsxJob::getFblzt, SpcyConstant.BLZT_YB)
                .like(SpcySqsxJob::getFlcmc, SpcyFlowConstant.LCMC_LIKE_SPCYLC)
                .orderByDesc(SpcySqsxJob::getFfssj));

        if (CollectionUtil.isNotEmpty(jobList)){
            return jobList.get(0);
        }

        return null;
    }

    /**
     * 获取申请事项-流转记录
     */
    public List<FlowJobHistoryDto> getJobListBySqsxId(String sqsxid){
        /*LambdaQueryWrapper<SpcySqsxJob> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SpcySqsxJob::getFpid, sqsxid);
        queryWrapper.like(SpcySqsxJob::getFlcmc, SpcyFlowConstant.LCMC_LIKE_SPCYLC);
        queryWrapper.orderByAsc(SpcySqsxJob::getFfssj);
        queryWrapper.orderByAsc(SpcySqsxJob::getCreateTime);
        List<SpcySqsxJob> jobList = spcySqsxJobService.list(queryWrapper);*/

        return spcySqsxJobService.selectHistoryListByFpidAndFlcmc(sqsxid, SpcyFlowConstant.LCMC_LIKE_SPCYLC);
    }

    /**
     * 获取下一个环节名称和待办人
     * @param sqsx 申请事项
     * @param sqsxid 申请事项id
     * @param job 流程任务
     * @param jobid 流程任务id
     * @return
     * {
     *     dbrId
     *     dbr:
     *     nextNode：下流程结点
     *     handlePageUrl：办理页面路径
     * }
     */
    public Map getNowJobInNextDbrAndHandlePageUrl(SpcySqsxBasic sqsx,String sqsxid,String jobid,SpcySqsxJob job){
        if (sqsx == null){
            sqsx = spcySqsxBaiscService.selectSqsxById(sqsxid);
        }

        if (job == null && StringUtils.isNotBlank(jobid)){
            job = spcySqsxJobService.getById(jobid);
        }

        String flowCode = SpcyFlowConstant.getFlowCodeByYwflcode(sqsx.getFywflcode(), SpcyConstant.SQSX_BASIC_XZSPZT_YES);
        return flowNodeService.getNowJobInNextDbrAndHandlePageUrl(flowCode, job, null);
    }

    /**
     * 获取对应流程结点的办理页面路径
     * @param jobid 当前流程任务id
     */
    public SysFlowPage getHandlePageUrl(String jobid){
        return flowNodeService.getHandlePageUrl(jobid);
    }

    /**
     * 提交流程
     * @param sqsxid 申请事项id
     * @param jobid 流程任务id
     * @param job 当前流程任务
     * @param opinion 办理意见
     * @param nextNodeName 下环节结点名称
     * @param nextNodeId 下环节结点id
     * @param nextNodeDbrIds 下环节待办人
     * @return
     */
    public Result passJob(String sqsxid,String jobid,SpcySqsxJob job, String opinion,String nextNodeName,String nextNodeId,String nextNodeDbrIds){
        if (job == null){
            job = spcySqsxJobService.getById(jobid);
        }
        String jobNodeName = job.getFhjmc(); // 当前环节名称
        Result httpResult = null;

        // 经办人阅知提醒
        if (StringUtils.isNotBlank(jobNodeName) && jobNodeName.equals(SpcyFlowConstant.HJMC_JBRYZTX)){
            //办理掉当前环节
            httpResult = flowNodeService.bjCommonJob(jobid, job, opinion);
            if (!httpResult.isSuccess()){
                return httpResult;
            }

            return Result.ok();
        }

        String ywflCode = busService.getYwflCode(sqsxid); // 获取业务分类编码
        String flowCode = SpcyFlowConstant.getFlowCodeByYwflcode(ywflCode, SpcyConstant.SQSX_BASIC_XZSPZT_YES);
//        if (ywflCode.equals(SpcyConstant.YWFL_CODE_YPSC)) {

            // 指定环节跳转
            /*if (StringUtils.isNotBlank(nextNodeName)){
                if (nextNodeName.equals(SpcyFlowConstant.HJMC_ZHPD) || nextNodeName.equals(SpcyFlowConstant.HJMC_FAZZ)){
                    SysFlowNode nowNode = sysFlowNodeService.getNowNodeById(job.getFnodeid());
                    if (nowNode != null){
                        SysFlowNode zdNode = sysFlowNodeService.getZdNodeByLcmbId(nowNode.getFlcmbid(), nextNodeName);
                        nextNodeId = zdNode.getId();
                    }
                }
            }*/

//            if (StringUtils.isNotBlank(jobNodeName) && jobNodeName.equals(SpcyFlowConstant.HJMC_YSQR)){
            if (StringUtils.isNotBlank(jobNodeName) && jobNodeName.equals(SpcyFlowConstant.HJMC_ZHPD)){
                //办理掉当前环节
                httpResult = flowNodeService.doJob(job, opinion);
            }else {
                httpResult = flowNodeService.passJob(flowCode, sqsxid, jobid, opinion, nextNodeId, nextNodeDbrIds);
            }

//        }
        /*else {

            // 指定环节跳转
            if (StringUtils.isNotBlank(nextNodeName)){
                if (nextNodeName.equals(SpcyFlowConstant.HJMC_ZHPD)){
                    SysFlowNode nowNode = sysFlowNodeService.getNowNodeById(job.getFnodeid());
                    if (nowNode != null){
                        SysFlowNode zdNode = sysFlowNodeService.getZdNodeByLcmbId(nowNode.getFlcmbid(), nextNodeName);
                        nextNodeId = zdNode.getId();
                    }
                }
            }

            if (StringUtils.isNotBlank(jobNodeName) && jobNodeName.equals(SpcyFlowConstant.HJMC_YSQR)){
                //办理掉当前环节
                httpResult = flowNodeService.doJob(job, opinion);
            }else {
                httpResult = flowNodeService.passJob(flowCode, sqsxid, jobid, opinion, nextNodeId, nextNodeDbrIds);
            }

            httpResult = flowNodeService.passJob(flowCode, sqsxid, jobid, opinion, nextNodeId, nextNodeDbrIds);
        }*/

        if (!httpResult.isSuccess()){
            return httpResult;
        }

        return Result.ok("success");
    }

    /**
     * 事项科室内部转办
     * @param jobid:当前流程任务jobid; ksfl: 选择科室分类
     */
    public void innerChangeFlowJob(String jobid,String ksfl){

        if (StringUtils.isBlank(jobid)){
            throw new BusinessException("当前流程任务id不能为空");
        }

        if (StringUtils.isBlank(ksfl)){
            throw new BusinessException("请选择需要转办的科室");
        }

        CurrentUserVo currentUser = GetCurrentUserUtils.getCurrentUser();
        if (currentUser == null){
            throw new BusinessException("登录已失效，请重新登录");
        }

        SpcySqsxJob job = spcySqsxJobService.getById(jobid);
        if (job == null){
            throw new BusinessException("当前流程任务不存在，请刷新重试");
        }
        String sqsxid = job.getFpid();

        // 审查模式
        String scms = "";
        if (StringUtils.isBlank(ksfl)){
            scms = SpcyConstant.SQSX_SCMS_XCJC;
        } else if (ksfl.equals(SpcyConstant.YWFL_CODE_YLQX)){
            scms = SpcyConstant.SQSX_SCMS_SCJCANBJSSC;
        }else if (ksfl.equals(SpcyConstant.YWFL_CODE_YPZC)){
            scms = SpcyConstant.SQSX_SCMS_SCJCANBJSSC;
        }else if (ksfl.equals(SpcyConstant.YWFL_CODE_HZP)){
            scms = SpcyConstant.SQSX_SCMS_SCJCANBJSSC;
        }else if (ksfl.equals(SpcyConstant.YWFL_CODE_YPZCLC)){
            scms = SpcyConstant.SQSX_SCMS_SCJCANBJSSC;
        }else if (ksfl.equals(SpcyConstant.YWFL_CODE_YPSC)){
            scms = SpcyConstant.SQSX_SCMS_XCJC;
        }else if (ksfl.equals(SpcyConstant.YWFL_CODE_YPSC)){
            scms = SpcyConstant.SQSX_SCMS_XCJC;
        }else {
            scms = SpcyConstant.SQSX_SCMS_XCJC;
        }

        LambdaUpdateWrapper<SpcySqsxBasic> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(SpcySqsxBasic::getId, sqsxid);

        SpcySqsxBasic sqsx = new SpcySqsxBasic();
        sqsx.setFscms(scms);
        sqsx.setFsplx(SpcyConstant.Sp_type_Ns); // 默认内审
        spcySqsxBaiscService.update(sqsx, updateWrapper);

        flowNodeService.doJob(job,"内部转办");

        // 初始化流程
        Result result1 = this.initYwflJob(ksfl, sqsxid, currentUser, true);
        if (!result1.isSuccess()){
            throw new BusinessException(result1.getMessage());
        }

    }

    /**
     * 退回流程 - 指定环节
     */
    public Result returnZdJob(SpcyReturnVo spcyReturnVo){
        CurrentUserVo currentUser = GetCurrentUserUtils.getCurrentUser();
        if (currentUser == null){
            return Result.error("登录已失效，请重新登录！");
        }

        if (StringUtils.isBlank(spcyReturnVo.getJobid())){
            return Result.error("流程任务参数为空！");
        }

        if (StringUtils.isBlank(spcyReturnVo.getOpinion())){
            return Result.error("请填写退回意见！");
        }

        if (StringUtils.isBlank(spcyReturnVo.getShjid())){
            return Result.error("请选择退回环节！");
        }

        SpcySqsxJob previousJob = spcySqsxJobService.getById(spcyReturnVo.getShjid());
        if (previousJob == null){
            log.error("退回失败！选中的退回环节不存在！{}", spcyReturnVo.getShjid());
            return Result.error("退回失败！选中的退回环节不存在！");
        }

        // 退回功能
        Result result = flowNodeService.returnJob(spcyReturnVo.getJobid(), spcyReturnVo.getShjid(), previousJob, spcyReturnVo.getOpinion(), currentUser);
        if (result.isSuccess()){

            /*if (previousJob.getFhjmc().equals(SpcyFlowConstant.HJMC_CLSC)){
                spcyVerifyService.verifyClscNumberJobInBkb(previousJob.getFdbrid());
            }*/

            try {
                /** 清空主办人 */
                if (previousJob.getFhjmc().equals(SpcyFlowConstant.HJMC_RWSL)){
                    spcySqsxBaiscService.updateEmptyFzbrById(previousJob.getFpid());;
                }
            }catch (Exception e){
                log.error("审评查验流程退回错误：{}", previousJob.getFhjmc());
            }


            if (StringUtils.isNotBlank(spcyReturnVo.getSmgflag()) && (spcyReturnVo.getSmgflag().equals("是") || spcyReturnVo.getSmgflag().equals("true"))) {
                SpcySqsxJob newPreviousJob = (SpcySqsxJob) result.getResult();
                // 发送退回短信
                String nextNodeSmsContent = busService.getNextNodeSmsContent(newPreviousJob, null);
                busService.sendNextNodeSmsContent(newPreviousJob, nextNodeSmsContent);
            }
        }else {
            return Result.error(result.getMessage());
        }

        return Result.ok();
    }

    /**
     * 转办流程
     */
    public void transferSpcyFlowJob(SpcyReturnVo spcyReturnVo){
        CurrentUserVo currentUser = GetCurrentUserUtils.getCurrentUser();
        if (currentUser == null){
            throw new BusinessException("登录已失效，请重新登录！");
        }

        if (StringUtils.isBlank(spcyReturnVo.getJobid())){
            throw new BusinessException("流程任务参数为空！");
        }

        if (StringUtils.isBlank(spcyReturnVo.getDbrid())){
            throw new BusinessException("请选择办理人！");
        }

        if (StringUtils.isBlank(spcyReturnVo.getOpinion())){
            spcyReturnVo.setOpinion("内部转办");
        }

        Result result = flowNodeService.transferFlowJob(spcyReturnVo.getJobid(), spcyReturnVo.getDbrid(), spcyReturnVo.getOpinion(), currentUser);
        if (result.isSuccess()){
            if (StringUtils.isNotBlank(spcyReturnVo.getSmgflag()) && (spcyReturnVo.getSmgflag().equals("是") || spcyReturnVo.getSmgflag().equals("true"))) {
                SpcySqsxJob newPreviousJob = (SpcySqsxJob) result.getResult();
                // 发送退回短信
                String nextNodeSmsContent = busService.getNextNodeSmsContent(newPreviousJob, null);
                busService.sendNextNodeSmsContent(newPreviousJob, nextNodeSmsContent);
            }
        }
    }



    /**
     * 办结-补齐补正流程-创建上一环节
     */
    public SpcySqsxJob bjBqbzJob(SpcySqsxBasic sqsx, String sqsxid, SpcySqsxJob copyJob, String opinion){

        opinion = "补齐补正完成。";

        String blr = "";
        if (sqsx == null){
            sqsx = spcySqsxBaiscService.selectSqsxById(sqsxid);

            blr = Optional.ofNullable(sqsx.getFqymc()).orElseGet(()->"企业");
        }

        if (copyJob == null) {
            copyJob = this.getNowNodeSpcyJob(sqsxid, false, SpcyFlowConstant.HJMC_CLSC, false);
        }

        SpcySqsxJob newPreviousJob = flowNodeService.copyNewJob(SpcyConstant.BLZT_DB, sqsxid,
                "", "",
                "", "",
                copyJob, null,
                SpcyFlowConstant.ZDY_HJMC_BQBZ_NODE_FSRID, blr);

        /**
         * 接收返回的流程任务，如果返回的流程任务id不相等，发送短信
         * 发送下环节短信
         */
        busService.sendNextNodeSmsContent(newPreviousJob, "");

        /*SpcySqsxJob bjJob = this.getNowNodeSpcyJob(sqsxid,false, SpcyFlowConstant.ZDY_HJMC_BQBZ);
        if (bjJob != null) {
            String pid = bjJob.getFpid();

            Result result = flowNodeService.doJob(bjJob.getId(), bjJob, opinion, false, "", blr, "");
            if (!result.isSuccess()) {

                log.error("办结-补齐补正流程-创建上一环节失败：{}", result.getMessage());
                return null;
            } else {
                *//** 2024-02-27 注释 *//*
                *//*SpcySqsxJob newPreviousJob = flowNodeService.copyNewJob(SpcyConstant.BLZT_DB, pid,
                        "", "",
                        "", "",
                        copyJob, null,
                        SpcyFlowConstant.ZDY_HJMC_BQBZ_NODE_FSRID, blr);*//*

                return null;
            }
        }*/

        return null;
    }

    /**
     * 将待办人map转为List
     * @param map { dbrId: 待办人id ; dbr: 待办人 }
     */
    public List<AgentVo> getDbrListByMap(Map map){
        String dbrids = map.get("dbrId").toString(); // 待办人id
        String dbrs = map.get("dbr").toString(); // 待办人

        List<AgentVo> agentList = new ArrayList<>();

        if (StringUtils.isNotBlank(dbrids)) {
            String agentIds[] = dbrids.split(",|，");
            String agentNames[] = dbrs.split(",|，");

            for (int i = 0; i < agentIds.length; i++) {
                AgentVo agentVo = new AgentVo();
                agentVo.setDbrid(agentIds[i]);
                agentVo.setDbr(agentNames[i]);
                agentList.add(agentVo);
            }
        }

        return agentList;
    }

    /**
     * 政务服务系统 - 退回功能
     */
    public void zwfwxtReturnJob(XzspJkApiJsywbmthParamVo jsywbmthVo){
        /*String access_token = jsywbmthVo.getAccess_token();
        if (StringUtils.isBlank(access_token)){
            throw new BusinessException("access_token不能为空！");
        }*/
        XzspJkApiJsywbmthVo param = jsywbmthVo.getParam();

        if (StringUtils.isBlank(param.getSxsqjbxx_id())){
            throw new BusinessException("操作失败，事项申请基本信息id为空！");
        }

        if (StringUtils.isBlank(param.getThsj())){
            throw new BusinessException("操作失败，退回时间为空！");
        }

        // 申请事项
        List<SpcySqsxBasic> sqsxList = spcySqsxBaiscService.list(new LambdaQueryWrapper<SpcySqsxBasic>()
                .eq(SpcySqsxBasic::getFsxsqjbxxid, param.getSxsqjbxx_id()));

        if (CollectionUtils.isEmpty(sqsxList)){
            throw new BusinessException("操作失败，当前事项申请信息不存在！");
        }
        log.error("接受业务部门退回接口");

        String fywflcode = sqsxList.get(0).getFywflcode();
        String sqsxid = sqsxList.get(0).getId();


        SpcySqsxJob previousJob = null; // 指定退回环节-流程任务
        String returnJobNode = ""; // 指定退回环节 - 各科室
        if (StringUtils.isBlank(fywflcode)){
            // 综合评定 - 环节
            returnJobNode = SpcyFlowConstant.HJMC_ZHPD;

        }else if (fywflcode.equals(SpcyConstant.YWFL_CODE_YLQX)){
            // 医疗器械 - 科室复核
            returnJobNode = SpcyFlowConstant.HJMC_ZHPD;

        }else {
            // 综合评定
            returnJobNode = SpcyFlowConstant.HJMC_ZHPD;
        }

        /** 查询是否存在待办流程 */
        /*List<SpcySqsxJob> jobList = spcySqsxJobService.list(new LambdaQueryWrapper<SpcySqsxJob>()
                .eq(SpcySqsxJob::getFpid, sqsxid)
                .ne(SpcySqsxJob::getFblzt, SpcyConstant.BLZT_YB)
                .like(SpcySqsxJob::getFlcmc, SpcyFlowConstant.LCMC_LIKE_SPCYLC));

        if (CollectionUtils.isEmpty(jobList)){*/
            // 综合评定 - 环节
        List<SpcySqsxJob> zdJobList = spcySqsxJobService.list(new LambdaQueryWrapper<SpcySqsxJob>()
                .eq(SpcySqsxJob::getFpid, sqsxid)
                .eq(SpcySqsxJob::getFhjmc, returnJobNode)
                .eq(SpcySqsxJob::getFblzt, SpcyConstant.BLZT_YB)
                .orderByDesc(SpcySqsxJob::getFfssj));
        if (CollectionUtils.isNotEmpty(zdJobList)){
            previousJob = zdJobList.get(0);
        }else {
            log.error("接受业务部门退回接口: 不存在指定环节【"+returnJobNode+"】");
            return;
        }
        /*} else {
            log.error("接受业务部门退回接口: 发送短信-指定环节【"+returnJobNode+"】");

            String nextNodeSmsContent = "";
            if (StringUtils.isNotBlank(param.getThyj())) {
                nextNodeSmsContent += "政务服务退回事项-退回意见："+param.getThyj();
            }
            if (StringUtils.isNotBlank(param.getThsj())){
                nextNodeSmsContent += "退回时间："+param.getThsj();
            }
            busService.sendNextNodeSmsContent(jobList.get(0),nextNodeSmsContent);

            return;
        }*/

        if (previousJob != null) {

            /**
             * 创建退回环节流程任务
             */
            String fsrid = "";
            String fsrmc = "";
            try {
                fsrid = sqsxList.get(0).getFxzspysrid();
                fsrmc = sqsxList.get(0).getFxzspysrmc() + "/" + sqsxList.get(0).getFxzspysrbm();
            }catch (Exception e){
                log.error("接受业务部门退回接口：{}", e.getMessage());
            }


            // 创建业务部门退回已办
            try {
                flowNodeService.copyYbJob(sqsxid,
                        "ZWFWYWBMID", "业务部门退回",
                        fsrid, fsrmc,
                        previousJob, null,
                        fsrid, fsrmc,
                        param.getThyj(), SpcyConstant.BLZT_YB
                        );
            }catch (Exception e){
                log.error("接受业务部门退回接口-创建业务部门退回已办错误：{}", e.getMessage());
            }

            /** 创建待办 */
            SpcySqsxJob newPreviousJob = flowNodeService.copyNewJob(SpcyConstant.BLZT_TH, sqsxid,
                    "", "",
                    "", "",
                    previousJob, null,
                    fsrid, fsrmc,
                    "");

            /** 发送退回短信 */
            String nextNodeSmsContent = busService.getNextNodeSmsContent(newPreviousJob, null);
            if (StringUtils.isNotBlank(param.getThyj())) {
                nextNodeSmsContent += "政务服务退回事项-退回意见：" + param.getThyj();
            }
            if (StringUtils.isNotBlank(param.getThsj())) {
                nextNodeSmsContent += "，退回时间：" + param.getThsj();
            }
            busService.sendNextNodeSmsContent(newPreviousJob, nextNodeSmsContent);

        }
    }


    /**
     * 获取当前流程任务相关信息
     * @param jobid 流程任务id
     * @return
     * {
     *     sqsx：申请事项
     *     qy：企业
     *     job：当前流程任务
     *     jobHistoryList：流程记录历史
     *     nextNodeDbrList: 下环节办理人
     *     nextNode：下环节结点名称
     *     nextNodeId：下环节结点id
     *     isZZState:  组长状态（true：组长）
     *     isRwfpFlag：现场检查分配任务状态（true:需分配任务；）
     * }
     */
    public Map getJobConcernByJobId(String jobid, String sqsxid){
        Map map = new HashMap();

        SpcySqsxJob job = null;
        if (StringUtils.isBlank(jobid)){
//            job = spcyFlowService.getNewSpcyJobDb(sqsxid);
        }else {
            job = spcySqsxJobService.getById(jobid);

            if (job == null){
                throw new BusinessException("当前流程任务不存在！");
            }else {

                // 当前流转记录
                if (job.getFlcsfkb().equals(SpcyFlowConstant.JOB_LCSFKB_BKB)){
                    throw new BusinessException("当前流程任务不可办，正处于队列中！");
                }

                if (StringUtils.isBlank(sqsxid) && job != null){
                    sqsxid = job.getFpid();
                }

            }
        }

        if (StringUtils.isBlank(sqsxid)){
            throw new BusinessException("当前流程任务业务参数为空！");
        }

        // 申请事项基本信息
        SpcySqsxBasic sqsx = spcySqsxBaiscService.getById(sqsxid);
        if (sqsx == null){
            return map;
        }else {
            boolean isUpdate = false;
            if (sqsx.getFslsj() == null) {
                sqsx.setFslsj(new Date());
                isUpdate = true;
            }

            // 获取申请事项-对应的业务分类
            if (StringUtils.isBlank(sqsx.getFjclx())){
                String jclx = busService.getDeptJclxBySxmc(sqsx.getFsxmc(), sqsx.getFywflcode());
                if (StringUtils.isNotBlank(jclx)){
                    sqsx.setFjclx(jclx);
                    isUpdate = true;
                }
            }

            // 计算申请事项-完成时限
            if (sqsx.getFwcsx() == null || sqsx.getFwcsx() == 0){
                int wcsx = flowJobBlsxService.initSqsxBlsxBySqsxId(sqsx);
                if (wcsx != 0) {
                    sqsx.setFwcsx(wcsx);
                    sqsx.setFsysx(String.valueOf(wcsx));
                    isUpdate = true;
                }
            }

            // 计算截止日期
            if (sqsx.getFjzrq() == null) {
                Date jzrq = flowJobBlsxService.jsSqsxJzrq(sqsx);
                if (jzrq != null){
                    sqsx.setFjzrq(jzrq);
                    isUpdate = true;
                }
            }

            /*try {
                if (StringUtils.isBlank(sqsx.getFszdq()) && StringUtils.isBlank(sqsx.getFjcdz())) {
                    sqsx = busService.genZwfwQySzdq(sqsx, 0);
                    isUpdate = true;

                } else if (StringUtils.isBlank(sqsx.getFszdq()) && StringUtils.isNotBlank(sqsx.getFjcdz())) {
                    sqsx = busService.genZwfwQySzdq(sqsx, 1);
                    isUpdate = true;

                } else if (StringUtils.isNotBlank(sqsx.getFszdq()) && StringUtils.isBlank(sqsx.getFjcdz())) {
                    sqsx = busService.genZwfwQySzdq(sqsx, 2);
                    isUpdate = true;
                }
            }catch (Exception e){
                log.error("政务数据库连接问题：{}", e.getMessage());
            }*/

            if (isUpdate) {
                spcySqsxBaiscService.updateById(sqsx);
            }
        }

        // 企业相关信息
        SpcyQyJbxx qyJbxx = null;
        if (sqsx != null && StringUtils.isNotBlank(sqsx.getFqyid())){
            qyJbxx = spcyQyJbxxService.getById(sqsx.getFqyid());
        }

        map.put("sqsx", sqsx); // 申请事项基本信息
        map.put("qy", qyJbxx); // 企业基本信息
        map.put("job", job); // 当前流转记录

        map.put("jobHistoryList", this.getJobListBySqsxId(sqsxid)); // 流程任务流传记录

        // 获取下环节待办人
        if (job != null) {

            // 查询短信回复
            if (job.getFhjmc().equals(SpcyFlowConstant.HJMC_FAZZ)) {
                xpryTimedTasksService.verifySendSmsInXpjlHfzt(sqsxid);
            }

            // 如果当前为现场检查：并且为检查员为组长
            if (job.getFhjmc().equals(SpcyFlowConstant.HJMC_XCJC)){

                // 验证是否为检查员组长，如果为组长分配
                CurrentUserVo currentUser = GetCurrentUserUtils.getCurrentUser();
                boolean isZZState = spcyVerifyService.verifyNowUserIsXpryZz(sqsxid, currentUser.getId());
                boolean isRwfpFlag = false; // 默认不分配
                // true: 需要分配任务; false: 不需要分配任务
                if (sqsx != null && (StringUtils.isBlank(sqsx.getFxcjcrwfpzt())
                        || !sqsx.getFxcjcrwfpzt().equals(SpcyCommonConstant.XCJC_RWFPZT_YFP))){
                    isRwfpFlag = true;
                }

                map.put("isZZState", isZZState);  // true：为组长
                map.put("isRwfpFlag", isRwfpFlag); // true: 需要分配任务;
            }

            try {
                if (StringUtils.isNotBlank(job.getFlcmc())){
                    if (job.getFlcmc().contains(SpcyFlowConstant.THZWFW_LCMC)) {
                        map.putAll(thzwYpscFlowService.getNextNodeDbr(jobid, job));

                    }else {
                        map.putAll(this.getNextNodeDbr(sqsx, sqsxid, jobid, job));

                    }
                }else {
                    map.putAll(this.getNextNodeDbr(sqsx, sqsxid, jobid, job));
                }
            }catch (Exception e){
                log.error("查询流程任务详情-根据流程任务id-获取下环节待办人错误：{}", e.getMessage());
            }

        }

        // 日常监管对象
        map.put("rcjg", spcySqsxRcjgService.selectRcjgById(sqsxid, null, null, sqsx));

        return map;
    }

    /**
     * APP-获取当前流程任务相关信息
     * */
    public Map getAppJobConcernByJobId(String jobid, String sqsxid){
        Map map = new HashMap();

        SpcyJobXqVo job = null;
        if (StringUtils.isBlank(jobid)){

        }else {
            job = spcySqsxJobService.selectJobInfoById(jobid);

            if (job == null){
                throw new BusinessException("当前流程任务不存在！");
            }else {
                if (StringUtils.isBlank(sqsxid) && job != null){
                    sqsxid = job.getFpid();
                }
            }
        }

        SpcySqsxBasic sqsx = spcySqsxBaiscService.selectSqsxInfoById(sqsxid);
        map.put("sqsx", sqsx); // 申请事项基本信息
        map.put("job", job);

        // 如果当前为现场检查：并且为检查员为组长
        if (job != null) {
            if (job.getFhjmc().equals(SpcyFlowConstant.HJMC_XCJC)) {

                // 验证是否为检查员组长，如果为组长分配, true：为组长
                map.put("isZZState", spcyVerifyService.verifyNowUserIsXpryZz(sqsxid, GetCurrentUserUtils.getCurrentUserId()));
            }
        }

        return map;
    }

    /**
     * 获取下环节待办人
     * @param sqsx
     * @param sqsxid
     * @param jobid
     * @param job
     * @return
     */
    public Map getNextNodeDbr(SpcySqsxBasic sqsx,String sqsxid,String jobid,SpcySqsxJob job){
        Map map = new HashMap();

        Map nextDbr = this.getNowJobInNextDbrAndHandlePageUrl(sqsx, sqsxid, jobid, job);
        String nextNodeId = ""; // 下结点id
        String nextNode = "办结"; // 下结点名称
        if (nextDbr.get("nextNode") != null) {
            SysFlowNode nextFlowNode = (SysFlowNode) nextDbr.get("nextNode");
            nextNodeId = nextFlowNode.getId();
            nextNode = nextFlowNode.getFjdmc();
        }
        List<AgentVo> dbrListByMap = this.getDbrListByMap(nextDbr);

        if (job != null) {
            if (job.getFhjmc().equals(SpcyFlowConstant.HJMC_RWSL)){
                /** 日常监管验证是否跳转环节 */
                boolean jumpFhjmc = spcySqsxBaiscService.getSqsxRcjgAndZxjcJumpHjmc(sqsx);
                if (jumpFhjmc){
                    nextNode = SpcyFlowConstant.HJMC_FAZZ;
                    nextNodeId = nextNode;

                    Map dbrMap = getZbrBySqsxId(sqsxid);
                    if (dbrMap.get("dbrId") == null){
                        // 经办人
                        String deptName = SpcyConstant.getYwclNameByCode(sqsx.getFywflcode());
                        Map dbrMap2 = getKsjbrByDeptName(deptName);
                        dbrListByMap = this.getDbrListByMap(dbrMap2);
                    }else {
                        dbrListByMap = this.getDbrListByMap(dbrMap);
                    }
                }
            }
            else if (job.getFhjmc().equals(SpcyFlowConstant.HJMC_CLSCFH)) {
                if (StringUtils.isNotBlank(sqsx.getFclscms()) && sqsx.getFclscms().equals(SpcyCommonConstant.SQSX_CLSCMS_NO_XCJC)) {
                    nextNode = SpcyFlowConstant.HJMC_ZHPD;
                    nextNodeId = nextNode;
                    Map dbrMap = getZbrBySqsxId(sqsxid);
                    dbrListByMap = this.getDbrListByMap(dbrMap);
                }
            }
        }

        map.put("nextNodeDbrList", dbrListByMap); // 下环节待办人list

        map.put("nextNode", nextNode); // 下流程结点名称
        map.put("nextNodeId", nextNodeId); // 下流程结点id

        return map;
    }

    /**
     * 获取对应科室的经办人
     * @param sqsxid 申请事项id
     * @param deptName 部门名称
     * @return
     * dbrList
     */
    public Map getDeptJbrList(String sqsxid, String deptName){
        if (StringUtils.isBlank(sqsxid) && StringUtils.isBlank(deptName)){
            throw new BusinessException("操作失败，缺少部门参数！");
        }

        if (StringUtils.isBlank(deptName)) {
            if (StringUtils.isBlank(sqsxid)){
                throw new BusinessException("事项参数为空!");
            }

            SpcySqsxBasic sqsx = spcySqsxBaiscService.selectSqsxById(sqsxid);
            if (sqsx == null) {
                throw new BusinessException("当前申请事项不存在！");
            }
            deptName = sqsx.getFywflname();
        }

        List<AgentVo> dbrListByMap = new ArrayList<>();

        if (StringUtils.isNotBlank(deptName)){
            // 获取对应科室经办人
            Map kzjbrMap = getKsjbrByDeptName(deptName);
            dbrListByMap = getDbrListByMap(kzjbrMap);
        }

        Map map = new HashMap();
        map.put("dbrList",dbrListByMap); // 待办人list
        return map;
    }

    /** 获取同意选派人员列表 */
    public List<SpcySqsxXpjl> getTyXpryList(String sqsxid, String flowType){
        return spcySqsxXpjlService.getTyXpXpjlList(sqsxid, flowType);
    }

    /**
     * 获取审评查验流程-当前处在的环节-流程任务
     * @param sqsxid 申请事项id
     * @param isFazz 查询方案制作环节流程-主办人
     * @param hjmc 环节名称
     */
    public SpcySqsxJob getNowNodeSpcyJob(String sqsxid, boolean isFazz, String hjmc){

        return getNowNodeSpcyJob(sqsxid, isFazz, hjmc, true);
    }
    /**
     * 获取审评查验流程-当前处在的环节-流程任务
     * @param isFazz 查询方案制作环节流程-主办人
     * @param hjmc 环节名称
     * @param isRwsl 是否查询任务受理
     */
    public SpcySqsxJob getNowNodeSpcyJob(String sqsxid, boolean isFazz, String hjmc, boolean isRwsl){

        LambdaQueryWrapper<SpcySqsxJob> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(SpcySqsxJob::getFpid, sqsxid);

        if (isFazz){
            queryWrapper.eq(SpcySqsxJob::getFhjmc, SpcyFlowConstant.HJMC_FAZZ);
        }else {
            if (org.apache.commons.lang3.StringUtils.isNotBlank(hjmc)){
                queryWrapper.eq(SpcySqsxJob::getFhjmc, hjmc);
            }else {
                queryWrapper.ne(SpcySqsxJob::getFblzt, SpcyConstant.BLZT_YB);
            }
        }

//        queryWrapper.like(SpcySqsxJob::getFlcmc, SpcyFlowConstant.LCMC_LIKE_SPCYLC);
        queryWrapper.orderByAsc(SpcySqsxJob::getFfssj);

        List<SpcySqsxJob> jobList = spcySqsxJobService.list(queryWrapper);

        if (CollectionUtils.isNotEmpty(jobList)){
            return jobList.get(0);
        }else{
            if (isRwsl) {
                LambdaQueryWrapper<SpcySqsxJob> queryWrapper2 = new LambdaQueryWrapper();
                queryWrapper.eq(SpcySqsxJob::getFhjmc, SpcyFlowConstant.HJMC_RWSL);
                queryWrapper2.eq(SpcySqsxJob::getFpid, sqsxid);
                queryWrapper2.like(SpcySqsxJob::getFlcmc, SpcyFlowConstant.LCMC_LIKE_SPCYLC);
                queryWrapper2.orderByAsc(SpcySqsxJob::getFfssj);
                List<SpcySqsxJob> job2List = spcySqsxJobService.list(queryWrapper2);
                if (CollectionUtils.isNotEmpty(job2List)) {
                    return job2List.get(0);
                }
            }
        }

        return null;
    }

    /** 获取指定流程环节记录 */
    public SpcySqsxJob getCurrentJobNode(String fpid, String hjmc, boolean isOrderDesc){

        LambdaQueryWrapper<SpcySqsxJob> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(SpcySqsxJob::getFpid, fpid);

        if (StringUtils.isNotBlank(hjmc)){
            queryWrapper.eq(SpcySqsxJob::getFhjmc, hjmc);
        }else {
            queryWrapper.ne(SpcySqsxJob::getFblzt, SpcyConstant.BLZT_YB);
        }

        if (isOrderDesc) {
            queryWrapper.orderByDesc(SpcySqsxJob::getFfssj);
        }else {
            queryWrapper.orderByAsc(SpcySqsxJob::getFfssj);
        }
        List<SpcySqsxJob> jobList = spcySqsxJobService.list(queryWrapper);

        if (CollectionUtils.isNotEmpty(jobList)){
            return jobList.get(0);
        }

        return null;
    }

    /************************************************[ 一下为旧版本流程 ]**************************************************************/

    /**
     * 获取当前环节待办人
     * @param sqsxid 申请事项id
     * @param nodeName 环节名称
     * @param deptName 部门名称
     * @return
     */
    public Map getNodeDbr(String sqsxid,String nodeName, String deptName){
        Map map = new HashMap();
        String dbrId = "";
        String dbr = "";

        /** 获取对应科室 */
        deptName = SpcyConstant.getYwclNameByCode(spcySqsxBaiscService.getYwflCodeBySqsxId(sqsxid));

        // 任务录入
        if (nodeName.equals(SpcyFlowConstant.HJMC_RWLR)){
            // 经办人
//                Map kzMap = getKsjbrByDeptName(SpcyConstant.getYwclNameByCode(flowConstant.getFywflcode()));
            Map kzMap = getKsjbrByDeptName(deptName);
            dbrId = kzMap.get("dbrId").toString();
            dbr = kzMap.get("dbr").toString();
        }

        // 任务受理
        if (nodeName.equals(SpcyFlowConstant.HJMC_RWSL)){
            // 科室负责人
            Map kzMap = getKsfzrByDeptName(deptName);
            dbrId = kzMap.get("dbrId").toString();
            dbr = kzMap.get("dbr").toString();
        }

        // 任务分配
        if (nodeName.equals(SpcyFlowConstant.HJMC_RWFP)){
            // 部门主管
            Map kzMap = getbmzgByDeptName(deptName);
            dbrId = kzMap.get("dbrId").toString();
            dbr = kzMap.get("dbr").toString();
        }

        // 材料审查
        if (nodeName.equals(SpcyFlowConstant.HJMC_CLSC)){

            // 经办人
            /*Map kzMap = getKsjbrByDeptName(deptName);
            dbrId = kzMap.get("dbrId").toString();
            dbr = kzMap.get("dbr").toString();*/

            Map zbrMap = getZbrBySqsxId(sqsxid);
            if (zbrMap.get("dbrId") == null){
                // 经办人
                Map kzMap = getKsjbrByDeptName(deptName);
                dbrId = kzMap.get("dbrId").toString();
                dbr = kzMap.get("dbr").toString();
            }else {
                dbrId = zbrMap.get("dbrId").toString();
                dbr = zbrMap.get("dbr").toString();
            }
        }

        // 材料审查复核
        if (nodeName.equals(SpcyFlowConstant.HJMC_CLSCFH)){
            // 科室负责人
            Map kzMap = getKsfzrByDeptName(deptName);
            dbrId = kzMap.get("dbrId").toString();
            dbr = kzMap.get("dbr").toString();
        }


        // 方案制作
        if (nodeName.equals(SpcyFlowConstant.HJMC_FAZZ)){
            Map zbrMap = getZbrBySqsxId(sqsxid);
            if (zbrMap.get("dbrId") == null){
                // 经办人
                Map kzMap = getKsjbrByDeptName(deptName);
                dbrId = kzMap.get("dbrId").toString();
                dbr = kzMap.get("dbr").toString();
            }else {
                dbrId = zbrMap.get("dbrId").toString();
                dbr = zbrMap.get("dbr").toString();
            }
        }

        // 方案复核
        if (nodeName.equals(SpcyFlowConstant.HJMC_FAFH)){
            // 经办人
            Map kzMap = getKsjbrByDeptName(deptName);
            dbrId = kzMap.get("dbrId").toString();
            dbr = kzMap.get("dbr").toString();
        }

        // 方案审核
        if (nodeName.equals(SpcyFlowConstant.HJMC_FASH)){
            // 科室负责人
            Map kzMap = getKsfzrByDeptName(deptName);
            dbrId = kzMap.get("dbrId").toString();
            dbr = kzMap.get("dbr").toString();
        }

        // 方案审批
        if (nodeName.equals(SpcyFlowConstant.HJMC_FASP)) {
            // 分管领导
            Map kzMap = getKsFgldByDeptName(deptName);
            dbrId = kzMap.get("dbrId").toString();
            dbr = kzMap.get("dbr").toString();
        }

        // 现场检查
        if (SpcyFlowConstant.HJMC_JSSP.equals(nodeName) || nodeName.equals(SpcyFlowConstant.HJMC_XCJC)){
            Map xcjcMap = getXcjcRyBySqsxId(sqsxid,SpcyConstant.FLOW_TYPE_CY);
            dbrId = xcjcMap.get("dbrId").toString();
            dbr = xcjcMap.get("dbr").toString();
        }

        // 综合评定
        if (nodeName.equals(SpcyFlowConstant.HJMC_ZHPD)){
            Map zbrMap = getZbrBySqsxId(sqsxid);
            dbrId = zbrMap.get("dbrId").toString();
            dbr = zbrMap.get("dbr").toString();
        }

        // 综合评定复核
        if (nodeName.equals(SpcyFlowConstant.HJMC_ZHPD_FH)){
            // 经办人
            Map kzMap = getKsjbrByDeptName(deptName);
            dbrId = kzMap.get("dbrId").toString();
            dbr = kzMap.get("dbr").toString();
        }

        // 科室复核
        if (nodeName.equals(SpcyFlowConstant.HJMC_KSFH)){
            // 经办人
            Map kzMap = getKsfzrByDeptName(deptName);
            dbrId = kzMap.get("dbrId").toString();
            dbr = kzMap.get("dbr").toString();
        }

        // 移送确认
        if (nodeName.equals(SpcyFlowConstant.HJMC_YSQR)) {
            // 分管领导
            Map kzMap = getKsFgldByDeptName(deptName);
            dbrId = kzMap.get("dbrId").toString();
            dbr = kzMap.get("dbr").toString();
        }

        map.put("dbrId",dbrId);
        map.put("dbr",dbr);
        return map;
    }

    // 对应科室的 部门主管
    public Map getbmzgByDeptName(String deptName){
        Map map = new HashMap();
        String dbrId = "";
        String dbr = "";
        List<GetKsKz> ksKzObject = new ArrayList<>();
        ksKzObject = ycSysUserService.getKsKzObject(deptName, SpcyConstant.GW_NAME_BMZG);

        if (CollectionUtils.isNotEmpty(ksKzObject)) {
            for (GetKsKz ksKz : ksKzObject) {
                if (StringUtils.isNotBlank(dbrId)){
                    dbrId += ",";
                    dbr += ",";
                }
                dbrId += ksKz.getId();
                dbr += ksKz.getRealname();
            }
        }

        map.put("dbrId",dbrId);
        map.put("dbr",dbr);
        return map;
    }

    // 对应科室的 科室负责人
    public Map getKsfzrByDeptName(String deptName){
        Map map = new HashMap();
        String dbrId = "";
        String dbr = "";
        List<GetKsKz> ksKzObject = new ArrayList<>();
        ksKzObject = ycSysUserService.getKsKzObject(deptName, SpcyConstant.GW_NAME_KZ);
        if (CollectionUtils.isNotEmpty(ksKzObject)) {
            for (GetKsKz ksKz : ksKzObject) {
                if (StringUtils.isNotBlank(dbrId)){
                    dbrId += ",";
                    dbr += ",";
                }
                dbrId += ksKz.getId();
                dbr += ksKz.getRealname();
            }
        }

        map.put("dbrId",dbrId);
        map.put("dbr",dbr);
        return map;
    }

    // 对应科室的 经办人
    public Map getKsjbrByDeptName(String deptName){
        Map map = new HashMap();
        String dbrId = "";
        String dbr = "";
        List<GetKsKz> ksKzObject = new ArrayList<>();
        ksKzObject = ycSysUserService.getKsKzObject(deptName, SpcyConstant.GW_NAME_JBR);

        if (CollectionUtils.isNotEmpty(ksKzObject)) {
            for (GetKsKz ksKz : ksKzObject) {
                if (StringUtils.isNotBlank(dbrId)){
                    dbrId += ",";
                    dbr += ",";
                }
                dbrId += ksKz.getId();
                dbr += ksKz.getRealname();
            }
        }

        map.put("dbrId",dbrId);
        map.put("dbr",dbr);
        return map;
    }

    // 获取对应科室的 分管领导
    public Map getKsFgldByDeptName(String deptName){
        Map map = new HashMap();
        String dbrId = "";
        String dbr = "";

        YcSysUser fgldUserBydept = sysUserFgldService.getFgldUserBydept(deptName);
        if (fgldUserBydept != null) {
            dbrId = fgldUserBydept.getId();
            dbr = fgldUserBydept.getRealname();
        }

        map.put("dbrId",dbrId);
        map.put("dbr",dbr);
        return map;
    }

    /**
     * 获取主办人
     * @param sqsxId 申请事项id
     * @return
     * {
     *     dbrId: 待办人id
     *     dbr: 待办人
     * }
     */
    public Map getZbrBySqsxId(String sqsxId){
        Map map = new HashMap();
        String dbrId = null;
        String dbr = "";

        SqsxZbrVo zbrVo = spcySqsxBaiscService.selectFzbrById(sqsxId);
        if (zbrVo != null && StringUtils.isNotBlank(zbrVo.getFzbr())){

            dbrId = zbrVo.getFzbr();

            if (StringUtils.isNotBlank(zbrVo.getFjbrmc())){
                dbr = zbrVo.getFjbrmc();
            }else {
                List<String> userIdList =  StringPatternUtils.getListByIds(zbrVo.getFzbr());
                List<YcSysUser> userList = ycSysUserService.findRealnameListByIds(userIdList);
                for (int i = 0; i<userList.size(); i++){
                    if (StringUtils.isBlank(dbr)) {
                        dbr = userList.get(i).getRealname();
                    } else {
                        dbr += "," + userList.get(i).getRealname();
                    }
                }
            }
        }

        map.put("dbrId",dbrId);
        map.put("dbr",dbr);
        return map;
    }

    /**
     * 获取现场检查人员
     * @param sqsxId 申请事项id
     * @param flowType 查验/审评
     */
    public Map getXcjcRyBySqsxId(String sqsxId,String flowType){
        Map map = new HashMap();
        String dbrId = "";
        String dbr = "";

        // 同意选派记录
        List<SpcyXpryUserVo> xpjlList = spcySqsxXpjlService.getTyxpUserBeanListByFsqsxId(sqsxId);
        if (CollectionUtils.isNotEmpty(xpjlList)){
            for (SpcyXpryUserVo xpjl : xpjlList){
                if (StringUtils.isBlank(dbrId)){
                    dbrId += xpjl.getFuserid();
                    dbr += xpjl.getFjcyxm() + "(" + Optional.ofNullable(xpjl.getFssk()).orElseGet(() -> "组员") + ")";
                }else {
                    dbrId += "," + xpjl.getFuserid();
                    dbr += "," + xpjl.getFjcyxm() + "(" + Optional.ofNullable(xpjl.getFssk()).orElseGet(() -> "组员") + ")";
                }
            }
        }

        map.put("dbrId", dbrId);
        map.put("dbr", dbr);
        return map;
    }

    /**
     * 获取申请事项主办人/科室负责人
     * @param sqsx 申请事项
     * @return
     */
    public String getZbrHzKsfzrBySqsxid(SpcySqsxBasic sqsx){
        String dbrid = "";

        // 获取主办人
        Map zbrBySqsxId = getZbrBySqsxId(sqsx.getId());
        dbrid = zbrBySqsxId.get("dbrId").toString();

        if (StringUtils.isBlank(dbrid)) {
            // 科室负责人
            Map kzMap = getKsfzrByDeptName(SpcyConstant.getYwclNameByCode(sqsx.getFywflcode()));
            dbrid = kzMap.get("dbrId").toString();
        }

        return dbrid;
    }

}
